import {HttpStatus} from "@nestjs/common"
import {HttpException} from "@nestjs/common";
import {HttpCode} from "./code";
class Message {
  private INDEX_REGX =  /(?:{\$([\d\w_]+)}|%(\d+))/g;
  private INDEX_ARGS = null;
  constructor(){}
  REPLACE_INDEX(m, n1, n2){
    if (n2){ n1 = n2; }
    return (this.INDEX_ARGS.hasOwnProperty(n1) ? this.INDEX_ARGS[n1] : m);
  }
  getError (code, param?) {
    if (code === 0){
      return;
    }
    var message = null;
    try {
      //自定义错误信息和
       message = HttpCode && HttpCode[code] || HttpStatus&& HttpStatus[code]
    }catch (err){}
    // 如果有指定参数, 替换参数
    if (message && param){
      let INDEX_ARGS = param;
      message = message.replace(this.INDEX_REGX, this.REPLACE_INDEX);
    }
    return message;
  }
}

/**
 * 错误模块
 */
export class CodeErrorModule extends HttpException {
  /**
   * @param errCode 错误码
   * @param message 错误信息
   */
  constructor(errCode: number, message?: string) {
    super({code:errCode, message: new Message().getError(errCode,message)}, 200);  // 抛出的时候在 exception.getResponse()
  }
}
